<template>
  <div class="app-container xjAdd">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="demo-formParams">
      <p>新增文章</p>

      <el-card class="margin-bottom-15">
        <el-descriptions title="基本信息" :column="3" border></el-descriptions>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type">
                <el-option v-for="item in typeList" :key="item"  :value="item">{{ item }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否置顶" prop="isTop">
              <el-select v-model="form.isTop">
                <el-option value="1" label="置顶">置顶</el-option>
                <el-option value="0" label="不置顶">不置顶</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否有效" prop="del">
              <el-select v-model="form.del">
                <el-option value="0" label="有效">有效</el-option>
                <el-option value="1" label="无效">无效</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" placeholder="请输入排序，按数值降序" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="时间" prop="sj">
              <el-date-picker clearable
                v-model="form.sj"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片">
              <el-upload
                action="#"
                list-type="picture-card"
                :file-list="fileList"
                :auto-upload="false"
                :on-change="changeFileList">
                <i class="el-icon-plus"></i>


              <div slot="file" slot-scope="{file}" style="position: relative;height: 100%;">
                <img v-if="file.name && file.name.indexOf('.pdf') >0" class="el-upload-list__item-thumbnail" style="width: 84%; height: 84%; margin-left: 8%;" src="@/img/pdf.png" alt="">
                <img v-else style="width: 84%; height: 84%; margin-left: 8%; margin-top: 8%;" class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <div class="file-name" style="position: absolute; bottom: 0px; left: 4px; font-size: 12px; background: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ file.name }}</div>  
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file,fileList)">
                  <i class="el-icon-delete"></i>
                </span>
                </span>
                  
                  <!-- <el-button  
                    size="mini"  
                    type="danger"  
                    @click="handleRemove(file.name, fileList, index)"  
                  >删除</el-button>   -->
              </div> 

              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-form-item style="text-align: center; margin-left: 0">
        <el-button type="primary" @click="submitForm('form')">提交</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import { upload } from '@/api/common';
import {addArticle,getArticle,updateArticle} from'@/api/ptsj/article'

export default {
  name: 'add',
  data() {
    return {
      typeList:["部门共治","行业自治","平台协同","图片管理", "通知公告"],
      form: {
        title: '',
        content: '',
        type: '',
        isTop: '',
        sort: '',
        sj: '',
        del:'0'
      },
      id:"",
      fileList: [],
      fjBackList:[],
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' },
        ],
        isTop: [
          { required: true, message: '请选择是否置顶', trigger: 'change' },
        ],
        sort: [
          { required: true, message: '请输出排序', trigger: 'blur' },
        ],
        sj: [
          { required: true, message: '请选择时间', trigger: 'change' },
        ]
      },
      handleSjfkVisible: false,
    }
  },
  created() {
    if(this.$route.query.id){
      this.id = this.$route.query.id
      this.getArticle(this.id);
    }
  },
  methods: {

    handleRemove(file, fileList) {
      // console.log(file, fileList,this.fjBackList);
      let index = this.fjBackList.map(item => item.id).indexOf(file.glid);
      // console.log(index);
      if(index >= 0) {
        this.fjBackList.splice(index, 1);
        this.fileList.splice(index, 1);
      } else {
        let i = this.fileList.map(item => item.uid).indexOf(file.uid);
        // console.log(i)
        this.fileList.splice(i, 1);
      }
    },
    changeFileList(file, fileList) {
      this.fileList = fileList;
      // console.log(this.fileList)
    },
    getArticle(id){
      getArticle(id).then(response => {
        let that = this;
        this.form = response.data;
        this.fjBackList = response.data.fileList ? response.data.fileList : [];
        // console.log(response.data.fileList)
        response.data.fileList.forEach(item=>{
          that.fileList.push({
            name:item.originalfilename,
            url:'/api'+item.filename,
            glid: item.id,
            uid: item.uid
          });
        })
        this.open = true;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.uploadImage();
          let params = this.form;
          params.fileList = this.fjBackList;
          if(this.id){
            params.id = this.id;
            await updateArticle(params).then(res => {
              if(res.code == 200) {
                this.$message.success('更新成功!');
                this.fileList = [];
                this.fjBackList = [];
                this.$refs.form.resetFields();
                setTimeout(() => {
                  this.$router.go(-1);
                }, 2000);
              }
            })
          }else{
            await addArticle(params).then(res => {
            if(res.code == 200) {
              this.$message.success('新增成功!');
              this.fileList = [];
              this.fjBackList = [];
              this.$refs.form.resetFields();
              setTimeout(() => {
                this.$router.go(-1);
              }, 2000);
            }
          })
          }



        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async uploadImage() {
      if(this.fileList.length > 0) {
        let addFileList = this.fileList.filter(item => {
          if(!item.glid) {
            return item;
          }
        })
        for(let i= 0; i< addFileList.length; i++) {
          let formData = new FormData();
          formData.append('file', addFileList[i].raw);
          await upload(formData).then(res => {
            try {
              this.fjBackList.push({
                filename: res.fileName,
                newfilename: res.newFileName,
                originalfilename: res.originalFilename,
                url: res.url,
              })
            } catch(error) {
              console.log(error)
            }
          })
        }
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.margin-bottom-15 {
  margin-bottom: 15px;
  margin-bottom: 50px;
}
</style>

<style scoped>
.xjAdd >>> .el-descriptions__title {
  font-weight: normal;
  border-left: 4px solid rgb(110, 172, 238);
  padding-left: 15px;
}
.xjAdd >>> .el-form-item__label {
  font-weight: normal;
}
</style>